package ldh.im.dto.codec.binery;

import io.netty.buffer.ByteBuf;
import ldh.im.dto.business.P2psTextMessage;
import ldh.im.dto.enmus.MessageType;

import java.util.HashSet;
import java.util.Set;

public class P2psTextMessageCodec extends AckToCodec<P2psTextMessage> {

    @Override
    public void encode(P2psTextMessage textMessage, ByteBuf byteBuf) {
        super.encode(textMessage, byteBuf);
        byteBuf.writeLong(textMessage.getFromUserId());
        byteBuf.writeShort(textMessage.getToUserIds().size());
        textMessage.getToUserIds().forEach(id-> byteBuf.writeLong(id));
        writeString(byteBuf, textMessage.getContent());
        byteBuf.writeByte(textMessage.getMessageType().getValue());
    }

    @Override
    public void decode(P2psTextMessage textMessage, ByteBuf byteBuf) {
        super.decode(textMessage, byteBuf);
        textMessage.setFromUserId(byteBuf.readLong());
        short size = byteBuf.readShort();
        Set<Long> userIdSet = new HashSet<>();
        for(int i=0; i<size; i++) {
            userIdSet.add(byteBuf.readLong());
        }
        textMessage.setToUserIds(userIdSet);
        textMessage.setContent(readString(byteBuf));
        textMessage.setMessageType(MessageType.getMessageTypeByValue(byteBuf.readByte()));
    }

    @Override
    public P2psTextMessage create() {
        return new P2psTextMessage();

    }
}
